//
//  AvatarView.swift
//  App_Common_Views
//
//  Created by 蒋晨成 on 2022/2/7.
//

import Base
import Chain
import Foundation
import Kingfisher
import SnapKit
import UIKit

public class AvatarView: Control {
    private let action: Action?
    private let option: Option

    private lazy var avatarImageView = UIImageView(image: nil, highlightedImage: nil)
        .x
        .contentMode(.scaleAspectFill)
        .corners(radius: option.cornerRadius)
        .border(color: .white, width: option.border.map(true: 1, false: 0))
        .instance

    public init(frame: CGRect = .zero, action: Action?, option: Option) {
        self.action = action
        self.option = option
        super.init(frame: frame)

        setup()
    }

    @available(*, unavailable)
    required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") }
}

private extension AvatarView {
    func setup() {
        avatarImageView.x.add(to: self).snp.makeConstraints {
            $0.edges.equalToSuperview()
        }
        switch action {
        case .none:
            isUserInteractionEnabled = false
        case .some:
            isUserInteractionEnabled = true
            addTarget(self, action: #selector(touchUpInsideAction(control:)), for: .touchUpInside)
        }
    }

    @objc
    func touchUpInsideAction(control _: Control) {
        action?(self)
    }
}

public extension AvatarView {
    func set(url: URL?, placeholder: UIImage? = nil) {
        avatarImageView.kf.setImage(with: url, placeholder: placeholder)
    }
}
